package com.qd.panda.service.stroke.order;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.common.panda.domain.entity.order.OrderGasDTO;
import com.qd.common.panda.domain.entity.order.OrderQueryDTO;
import com.qd.common.panda.domain.entity.order.TotalPreferentialAmountDTO;
import com.qd.common.panda.domain.entity.stroke.UserStrokeOrderGasDTO;
import com.qd.common.panda.domain.entity.stroke.preferential.UserStrokeOrderPreferentialLogDTO;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.mapper.stroke.UserStrokeOrderGasMapper;
import com.qd.panda.model.UserStrokeOrderGas;
import com.qd.panda.service.stroke.BigDecimalUtil;
import com.qd.panda.service.stroke.DisplayUtil;
import com.qd.system.service.dict.MbUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 加油订单
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserStrokeOrderGasService extends BaseService<UserStrokeOrderGasMapper, UserStrokeOrderGas> {

    private static final String PREFIX_ID = "panda_user_stroke_order_gas_orderId_{0}";

    private final RedisTemplateUtil<UserStrokeOrderGas> redisTemplateUtil;

    private final UserStrokeOrderPreferentialLogService userStrokeOrderPreferentialLogService;

    private final ObjectMapper objectMapper;

    private static QueryWrapper<OrderQueryDTO> getQueryWrapper(OrderQueryDTO orderQueryDTO) {
        final QueryWrapper<OrderQueryDTO> queryWrapper = new QueryWrapper<>();
        Integer month = orderQueryDTO.getMonth();
        if (null == month) {
            //默认查询一个月
            month = 1;
        }
        if (month < 1) {
            throw new ApiException("month异常");
        }
        if (month > 12) {
            throw new ApiException("只支持查询最近一年的数据");
        }
        final Date end = new Date();
        final DateTime start = DateUtil.offsetMonth(end, -month);
        queryWrapper.eq("o.order_type", DisplayUtil.ORDER_TYPE_4);
        queryWrapper.eq("o.pay_status", DisplayUtil.PAY_STATUS_1);
        queryWrapper.eq("o.user_id", SecurityUtils.getLoginUser().getUserId());
        queryWrapper.between("o.start_time", start, end);
        return queryWrapper;
    }

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderGasDTO save(UserStrokeOrderGasDTO dto) {
        final UserStrokeOrderGas model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserStrokeOrderGasDTO update(UserStrokeOrderGasDTO dto) {
        final UserStrokeOrderGas historyModel = Optional.ofNullable(getById(dto.getOrderId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserStrokeOrderGas model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<UserStrokeOrderGas> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<UserStrokeOrderGas> mList) {
        final List<String> ids = mList.stream().map(UserStrokeOrderGas::getOrderId).collect(toList());
        final List<UserStrokeOrderGas> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param orderId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String orderId) {
        final UserStrokeOrderGas historyModel = Optional.ofNullable(getById(orderId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(orderId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<UserStrokeOrderGas> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserStrokeOrderGasDTO dto) {
        final QueryWrapper<UserStrokeOrderGas> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param orderId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String orderId) {
        boolean exists = false;
        if (StringUtils.hasLength(orderId)) {
            final UserStrokeOrderGas model = getById(orderId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param orderId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderGas getById(String orderId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orderId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(orderId), UserStrokeOrderGas.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param orderId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderGasDTO getByIdDto(String orderId) {
        return Optional.ofNullable(getById(orderId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderGas getOne(UserStrokeOrderGasDTO dto) {
        final QueryWrapper<UserStrokeOrderGas> queryWrapper = createQueryWrapper(dto);
        UserStrokeOrderGas model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserStrokeOrderGasDTO getOneDto(UserStrokeOrderGasDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderGas> getList(UserStrokeOrderGasDTO dto) {
        final QueryWrapper<UserStrokeOrderGas> queryWrapper = createQueryWrapper(dto);
        final List<UserStrokeOrderGas> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserStrokeOrderGasDTO> getListDto(UserStrokeOrderGasDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserStrokeOrderGasDTO> page(Page<UserStrokeOrderGas> page, UserStrokeOrderGasDTO dto) {
        final QueryWrapper<UserStrokeOrderGas> queryWrapper = createQueryWrapper(dto, "t1.");
        final IPage<UserStrokeOrderGasDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 查询加油订单
     *
     * @param page          分页属性
     * @param orderQueryDTO 查询条件
     * @return 数据
     */
    @Transactional(readOnly = true)
    public IPage<OrderGasDTO> orderGasPage(IPage<OrderGasDTO> page, OrderQueryDTO orderQueryDTO) {
        final QueryWrapper<OrderQueryDTO> queryWrapper = getQueryWrapper(orderQueryDTO);
        queryWrapper.orderByDesc("o.start_time");
        final IPage<OrderGasDTO> iPage = baseMapper.orderGasPage(page, queryWrapper);
        queryWrapper.clear();
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        return iPage;
    }

    @Transactional(readOnly = true)
    public OrderGasDTO getOrderGasByOrderId(String orderId) {
        final OrderGasDTO orderGasDTO = Optional.ofNullable(getBaseMapper().getOrderGasByOrderId(orderId)).orElseThrow(() -> new ApiException("订单ID不存在"));
        final List<UserStrokeOrderPreferentialLogDTO> list = userStrokeOrderPreferentialLogService.getCategoryListByOrderId(orderId);
        if (!list.isEmpty()) {
            list.removeIf(userStrokeOrderPreferentialLogDTO -> userStrokeOrderPreferentialLogDTO.getFlag().equals(1));
            Map<String, UserStrokeOrderPreferentialLogDTO> map = new HashMap<>();
            for (UserStrokeOrderPreferentialLogDTO userStrokeOrderPreferentialLogDTO : list) {
                UserStrokeOrderPreferentialLogDTO dto = map.get(userStrokeOrderPreferentialLogDTO.getPreferentialCategory());
                if (null == dto) {
                    dto = new UserStrokeOrderPreferentialLogDTO();
                    dto.setPreferentialCategory(userStrokeOrderPreferentialLogDTO.getPreferentialCategory());
                    dto.setPreferentialCategoryDisplay(userStrokeOrderPreferentialLogDTO.getPreferentialCategoryDisplay());
                    dto.setDiscountAmount(userStrokeOrderPreferentialLogDTO.getDiscountAmount());
                    map.put(userStrokeOrderPreferentialLogDTO.getPreferentialCategory(), dto);
                } else {
                    Money money = new Money(dto.getDiscountAmount()).add(new Money(userStrokeOrderPreferentialLogDTO.getDiscountAmount()));
                    dto.setDiscountAmount(money.getAmount());
                }

            }
            ArrayNode arrayNode = objectMapper.createArrayNode();
            for (String key : map.keySet()) {
                ObjectNode jsonNode = objectMapper.createObjectNode();
                UserStrokeOrderPreferentialLogDTO userStrokeOrderPreferentialLogDTO = map.get(key);
                jsonNode.put("discountAmount", userStrokeOrderPreferentialLogDTO.getDiscountAmount());
                jsonNode.put("discountAmountDisplay", BigDecimalUtil.buildDefaultScale(userStrokeOrderPreferentialLogDTO.getDiscountAmount()).stripTrailingZeros().toPlainString());
                jsonNode.put("preferentialCategory", userStrokeOrderPreferentialLogDTO.getPreferentialCategory());
                jsonNode.put("preferentialCategoryDisplay", userStrokeOrderPreferentialLogDTO.getPreferentialCategoryDisplay());
                arrayNode.add(jsonNode);
            }
            orderGasDTO.setPreferentialList(arrayNode);
        }
        buildDisplay(orderGasDTO);
        return orderGasDTO;
    }

    /**
     * 查询优惠总金额
     *
     * @param orderQueryDTO 查询条件
     * @return 总金额
     */
    public TotalPreferentialAmountDTO totalPreferentialAmount(OrderQueryDTO orderQueryDTO) {
        final QueryWrapper<OrderQueryDTO> queryWrapper = getQueryWrapper(orderQueryDTO);
        TotalPreferentialAmountDTO totalPreferentialAmount = Optional.ofNullable(baseMapper.totalPreferentialAmount(queryWrapper)).orElse(new TotalPreferentialAmountDTO());
        queryWrapper.clear();
        if (null == totalPreferentialAmount.getOrderAmount()) {
            totalPreferentialAmount.setOrderAmount(new BigDecimal("0.00"));
            totalPreferentialAmount.setOrderAmountDisplay("0");
        } else {
            totalPreferentialAmount.setOrderAmountDisplay(BigDecimalUtil.buildDefaultScale(totalPreferentialAmount.getOrderAmount()).stripTrailingZeros().toPlainString());
        }
        if (null == totalPreferentialAmount.getDiscountAmount()) {
            totalPreferentialAmount.setDiscountAmount(new BigDecimal("0.00"));
            totalPreferentialAmount.setDiscountAmountDisplay("0");
        } else {
            totalPreferentialAmount.setDiscountAmountDisplay(BigDecimalUtil.buildDefaultScale(totalPreferentialAmount.getDiscountAmount()).stripTrailingZeros().toPlainString());
        }

        return totalPreferentialAmount;
    }

    private void buildDisplay(OrderGasDTO dto) {
        dto.setOrderAmountDisplay(Optional.ofNullable(dto.getOrderAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setPayAmountDisplay(Optional.ofNullable(dto.getPayAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setDiscountAmountDisplay(Optional.ofNullable(dto.getDiscountAmount()).map(amount -> BigDecimalUtil.buildDefaultScale(amount).stripTrailingZeros().toPlainString()).orElse(""));
        dto.setOrderTypeDisplay(DisplayUtil.getOrderTypeDisplay(dto.getOrderType()));
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserStrokeOrderGas model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrderId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserStrokeOrderGas> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrderId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserStrokeOrderGasDTO modelToDto(UserStrokeOrderGas model) {
        if (null == model) {
            return null;
        }
        final UserStrokeOrderGasDTO dto = new UserStrokeOrderGasDTO();
        dto.setOrderId(model.getOrderId());
        dto.setGasStationCompanyId(model.getGasStationCompanyId());
        dto.setGasStationCompanyName(model.getGasStationCompanyName());
        dto.setOctaneNumber(model.getOctaneNumber());
        dto.setNozzleNumber(model.getNozzleNumber());
        dto.setPrice(model.getPrice());
        dto.setSid(model.getSid());
        dto.setOilVolume(model.getOilVolume());
        dto.setStationType(model.getStationType());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserStrokeOrderGas dtoToModel(UserStrokeOrderGasDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserStrokeOrderGas model = new UserStrokeOrderGas();
        model.setOrderId(dto.getOrderId());
        model.setGasStationCompanyId(dto.getGasStationCompanyId());
        model.setGasStationCompanyName(dto.getGasStationCompanyName());
        model.setOctaneNumber(dto.getOctaneNumber());
        model.setNozzleNumber(dto.getNozzleNumber());
        model.setPrice(dto.getPrice());
        model.setSid(dto.getSid());
        model.setOilVolume(dto.getOilVolume());
        model.setStationType(dto.getStationType());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserStrokeOrderGasDTO dto) {
        dto.setStationTypeDisplay(MbUtil.idToDisplay(dto.getStationType()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserStrokeOrderGasDTO> modelToDtoList(List<UserStrokeOrderGas> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserStrokeOrderGas> dtoToModelList(List<UserStrokeOrderGasDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserStrokeOrderGas> createQueryWrapper(UserStrokeOrderGasDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserStrokeOrderGas> createQueryWrapper(UserStrokeOrderGasDTO dto, String tableAlias) {
        final QueryWrapper<UserStrokeOrderGas> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getGasStationCompanyId())) {
                queryWrapper.eq(tableAlias + "gas_station_company_id", dto.getGasStationCompanyId());
            }
            if (StringUtils.hasLength(dto.getGasStationCompanyName())) {
                queryWrapper.eq(tableAlias + "gas_station_company_name", dto.getGasStationCompanyName());
            }
            if (StringUtils.hasLength(dto.getNozzleNumber())) {
                queryWrapper.eq(tableAlias + "nozzle_number", dto.getNozzleNumber());
            }
            if (StringUtils.hasLength(dto.getSid())) {
                queryWrapper.eq(tableAlias + "sid", dto.getSid());
            }
        }
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserStrokeOrderGas> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserStrokeOrderGas> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserStrokeOrderGas::getOrderId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }
}